import express from 'express'
import cors from 'cors'
import helmet from 'helmet'
import morgan from 'morgan'
import compression from 'compression'
import rateLimit from 'express-rate-limit'
import dotenv from 'dotenv'
import path from 'path'
import { fileURLToPath } from 'url'

// 导入中间件和路由
import { errorHandler, notFound } from './middleware/errorHandler.js'
import { authenticateToken } from './middleware/auth.js'
import { initializeDatabase } from './config/database.js'
import { initializeDefaultAdmin } from './utils/admin.js'

// 导入路由
import authRoutes from './routes/auth.js'
import userRoutes from './routes/users.js'
import contentRoutes from './routes/content.js'
import blogRoutes from './routes/blog.js'
import analyticsRoutes from './routes/analytics.js'
import uploadRoutes from './routes/upload.js'

// 配置环境变量
dotenv.config()

const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)

const app = express()
const PORT = process.env.PORT || 3001

// 安全中间件
app.use(helmet({
  contentSecurityPolicy: {
    directives: {
      defaultSrc: ["'self'"],
      styleSrc: ["'self'", "'unsafe-inline'", "https://fonts.googleapis.com", "https://cdnjs.cloudflare.com"],
      fontSrc: ["'self'", "https://fonts.gstatic.com", "https://cdnjs.cloudflare.com"],
      scriptSrc: ["'self'", "'unsafe-inline'"],
      imgSrc: ["'self'", "data:", "https:", "http:"],
      connectSrc: ["'self'"],
      objectSrc: ["'none'"],
      mediaSrc: ["'self'"],
      frameSrc: ["'none'"]
    }
  },
  crossOriginEmbedderPolicy: false
}))

// CORS配置
app.use(cors({
  origin: process.env.NODE_ENV === 'production' 
    ? ['https://yangcun.icu', 'https://www.yangcun.icu']
    : ['http://localhost:3000', 'http://127.0.0.1:3000'],
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With']
}))

// 请求限制
const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15分钟
  max: 100, // 限制每个IP 15分钟内最多100个请求
  message: {
    error: '请求过于频繁，请稍后再试'
  },
  standardHeaders: true,
  legacyHeaders: false
})

const authLimiter = rateLimit({
  windowMs: 15 * 60 * 1000,
  max: 5, // 登录接口限制更严格
  message: {
    error: '登录尝试次数过多，请稍后再试'
  }
})

app.use('/api/', limiter)
app.use('/api/auth/login', authLimiter)

// 基础中间件
app.use(compression())
app.use(morgan('combined'))
app.use(express.json({ limit: '10mb' }))
app.use(express.urlencoded({ extended: true, limit: '10mb' }))

// 静态文件服务
app.use('/uploads', express.static(path.join(__dirname, '../uploads')))

// API路由
app.use('/api/auth', authRoutes)
app.use('/api/users', authenticateToken, userRoutes)
app.use('/api/content', contentRoutes)
app.use('/api/blog', blogRoutes)
app.use('/api/analytics', analyticsRoutes)
app.use('/api/upload', authenticateToken, uploadRoutes)

// 健康检查端点
app.get('/api/health', (req, res) => {
  res.json({
    status: 'ok',
    timestamp: new Date().toISOString(),
    uptime: process.uptime(),
    environment: process.env.NODE_ENV || 'development',
    version: '2.0.0'
  })
})

// API信息端点
app.get('/api/info', (req, res) => {
  res.json({
    name: '存存的小屋 API',
    version: '2.0.0',
    description: '二次元风格个人网站后端服务',
    author: '存存',
    endpoints: {
      auth: '/api/auth',
      users: '/api/users',
      content: '/api/content',
      blog: '/api/blog',
      analytics: '/api/analytics',
      upload: '/api/upload',
      health: '/api/health'
    }
  })
})

// 404处理
app.use(notFound)

// 错误处理
app.use(errorHandler)

// 启动服务器
const startServer = async () => {
  try {
    // 初始化数据库
    await initializeDatabase()
    
    // 初始化默认管理员账户
    await initializeDefaultAdmin()
    
    app.listen(PORT, () => {
      console.log(`🌸 存存的小屋 API 服务器启动成功！`)
      console.log(`📍 服务地址: http://localhost:${PORT}`)
      console.log(`🌍 环境: ${process.env.NODE_ENV || 'development'}`)
      console.log(`⏰ 启动时间: ${new Date().toLocaleString('zh-CN')}`)
    })
  } catch (error) {
    console.error('❌ 服务器启动失败:', error)
    process.exit(1)
  }
}

// 优雅关闭
process.on('SIGTERM', () => {
  console.log('收到 SIGTERM 信号，正在优雅关闭服务器...')
  process.exit(0)
})

process.on('SIGINT', () => {
  console.log('收到 SIGINT 信号，正在优雅关闭服务器...')
  process.exit(0)
})

// 未捕获的异常处理
process.on('uncaughtException', (error) => {
  console.error('未捕获的异常:', error)
  process.exit(1)
})

process.on('unhandledRejection', (reason, promise) => {
  console.error('未处理的 Promise 拒绝:', reason)
  process.exit(1)
})

startServer() 